package com.distribution.system.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.distribution.common.constant.Constants;
import com.distribution.common.core.domain.AjaxResult;
import com.distribution.common.core.domain.entity.SysMenu;
import com.distribution.common.core.domain.entity.SysUser;
import com.distribution.common.core.domain.model.LoginBody;
import com.distribution.common.exception.ServiceException;
import com.distribution.common.utils.SecurityUtils;
import com.distribution.common.utils.StringUtils;
import com.distribution.common.utils.http.HttpUtils;
import com.distribution.common.utils.sign.Base64;
import com.distribution.framework.web.service.SysLoginService;
import com.distribution.framework.web.service.SysPermissionService;
import com.distribution.system.domain.dto.PageAccessToken;
import com.distribution.system.domain.dto.UserBaseDto;
import com.distribution.system.service.ISysMenuService;
import com.distribution.system.service.ISysUserService;
import com.distribution.system.utils.EncryptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Slf4j
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService iSysUserService;
    @Value("${gzpt.appId}")
    private String gzptAppId;

    @Value("${gzpt.appSecret}")
    private String gzptAppSecret;

    @Value("${gzpt.oauth}")
    private String gzptOauth;
    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String password = EncryptionUtil.decodeBase64(loginBody.getPassword());
        String token = loginService.login(loginBody.getUsername(), password, loginBody.getCode(),
                loginBody.getUuid(),ajax);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 根据openId登录
     */
    @PostMapping("/loginByOpenId")
    public AjaxResult loginByOpenId(@RequestBody UserBaseDto userBaseDto)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = iSysUserService.getUserByOpenId(userBaseDto.getOpenId());
        if (user == null) {
            throw new ServiceException("查无绑定用户");
        }
        // 生成令牌
        String token = loginService.login(user.getUserName(), user.getPassword(), null,
                null,ajax);
        ajax.put(Constants.TOKEN, token);
        ajax.put("username", user.getUserName());
        ajax.put("password", user.getPassword());
        return ajax;
    }




    @PostMapping(value = "/h5Login")
    public AjaxResult h5Login(@RequestBody @Validated LoginBody loginBody){
        System.out.println("h5登录！");
        AjaxResult ajax = AjaxResult.success("登录成功");
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(),ajax);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    @PostMapping(value = "/validAuthCode")
    public AjaxResult validAuthCode(@RequestBody @Validated LoginBody loginBody){
        System.out.println("公众号h5登录！");
        if (StringUtils.isEmpty(loginBody.getOpenId())) {
            throw new ServiceException("openId不能为空");
        }
        AjaxResult ajax = AjaxResult.success();
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(),ajax);
        ajax.put(Constants.TOKEN, token);
        //更新openID到数据库中
        SysUser sysUser = iSysUserService.selectUserByUserName(loginBody.getUsername());
        if (sysUser.getOpenId() != null && !sysUser.getOpenId().equals(loginBody.getOpenId())) {
            throw new ServiceException("微信与绑定用户不匹配!");
        }
        if (sysUser.getOpenId() == null) {
            sysUser.setOpenId(loginBody.getOpenId());
            iSysUserService.updateUser(sysUser);
        }
        return ajax;
    }

    /**
     * 通过code获取客户OpenID
     */
    @PostMapping(value = "/getOpenId")
    public AjaxResult getOpenId(@RequestBody UserBaseDto userBaseDto) {
        String code =userBaseDto.getCode();
        String reqParams = "&appid=" + gzptAppId + "&secret=" + gzptAppSecret +
                "&code=" + code + "&grant_type=authorization_code";
        log.info("获取reqParams:" + reqParams);
        String accessToken = HttpUtils.sendGet(gzptOauth, reqParams);
        log.info("获取accessToken:" + accessToken);
        PageAccessToken at =  JSONObject.parseObject(accessToken,PageAccessToken.class);
        String openid = at.getOpenid();
        log.info("openId为:{}",openid);
        if (openid == null) {
            throw new ServiceException("获取openId失败!");
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("openId",openid);
        return ajax;
    }

    /**
     * 通过code获取客户OpenID
     */
    @PostMapping(value = "/wx/getOpenIdByCode")
    public AjaxResult getOpenIdByCode(@RequestBody String code) {
        String reqParams = "&appid=" + gzptAppId + "&secret=" + gzptAppSecret +
                "&code=" + code + "&grant_type=authorization_code";
        log.info("获取reqParams:" + reqParams);
        String accessToken = HttpUtils.sendGet(gzptOauth, reqParams);
        log.info("获取accessToken:" + accessToken);
        PageAccessToken at =  JSONObject.parseObject(accessToken,PageAccessToken.class);
        String openid = at.getOpenid();
        log.info("openId为:{}",openid);
        if (openid == null) {
            throw new ServiceException("获取openId失败!");
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("openId",openid);
        return ajax;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //System.out.println("user = " + user);
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
